package ShiYan1;

import secondweek.EmptyCollectionException;

import java.util.Arrays;

public class Substance {
    private final int DEFAULT_CAPACITY = 100;
    private int nTanXin;
    private String[] stack, temp;
    public Substance(){
        stack = new String[DEFAULT_CAPACITY];
        nTanXin = 0;
    }
    public void add(int substance){
        if (size() == stack.length) {
            expandCapacity();
        }
        stack[nTanXin] = String.valueOf(substance);
        nTanXin++;
    }
    private void expandCapacity(){
        stack = Arrays.copyOf(stack,stack.length + 1);
    }
    public void insert(int weizhi, int number){
        if(weizhi > nTanXin){
            System.out.println("插入位置超过元素长度，请确认好在输入！！");
        }
        else{
                temp = new String[size() - weizhi];
                int n = 0;

                for(int a = weizhi; a < size(); a++){
                    temp[n] = stack[a];
                    n++;
                }

                stack[weizhi] = String.valueOf(number);
                for(int b = 0; b < temp.length;b++){
                    stack[weizhi + b + 1] = temp[b];
                }
            }
        nTanXin++;
    }
    public void delete(int number) throws EmptyCollectionException {
        int num = 0, f = 0;
        if(isEmpty()) {
            throw new EmptyCollectionException("StackADT");
        }
        while(Integer.parseInt(stack[num]) != number){
            num++;
        }
        temp = new String[size() - num];
        for(int d = num; d < size(); d++){
            temp[f] = stack[d + 1];
            f++;
        }
        for(int s = 0; s < temp.length; s++){
            stack[num + s] = temp[s];
        }
        stack[size()] = null;
        nTanXin--;
    }
    public boolean isEmpty()
    {
        return nTanXin == 0;
    }
    public int size()
    {
        return nTanXin;
    }
    public void sort()
    {
        int min ,temp;
        for (int index = 0; index < nTanXin - 1; index++)
        {
            min = index;
            for (int scan = index + 1; scan < nTanXin; scan++) {
                if (Integer.parseInt(stack[scan]) < Integer.parseInt(stack[min]))
                    min = scan;
            }
            temp = Integer.parseInt(stack[min]);
            stack[min] = stack[index];
            stack[index] = String.valueOf(temp);
            System.out.print("第" + ( index + 1 ) + "次：（元素总数:" + nTanXin +"）");
            for(int a = 0; a < size(); a++){
                System.out.print(stack[a] +" ");
            }
            System.out.println();
        }
    }
    @Override
    public String toString()
    {
        String result = "";
        for(int num = 0; num < size(); num++) {
            result += stack[num] +" ";
        }
        return result;
    }
}
